package top.cardone.security.shiro.web.filter.authc.impl;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.CharEncoding;
import org.apache.shiro.web.filter.authc.UserFilter;
import top.cardone.context.util.CodeExceptionUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Writer;

/**
 * Created by yht on 16-2-2.
 */
@Log4j2
public class UserFilterImpl extends UserFilter {
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		if (!org.apache.commons.lang3.StringUtils.startsWith(request.getContentType(), org.springframework.http.MediaType.APPLICATION_JSON_VALUE)) {
			return super.onAccessDenied(request, response);
		}

		response.setCharacterEncoding(CharEncoding.UTF_8);
		response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);

		try (Writer out = response.getWriter()) {
			String requestURI = getPathWithinApplication(request);

			String json = CodeExceptionUtils.newString(requestURI, "000001", "请登录系统");

			out.write(json);

			out.flush();
		} catch (java.io.IOException e) {
			log.error(e.getMessage(), e);
		}

		return false;
	}
}